// src/store/modules/permission.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '@/router'

// 动态路由（需要权限控制的路由）
export const asyncRoutes = [
  {
    path: '/system',
    name: 'System',
    redirect: '/system/user',
    meta: { 
      title: '系统管理',
      requiresAuth: true,
      roles: ['admin'] // 只有管理员可以访问
    },
    children: [
      {
        path: 'user',
        name: 'UserManagement',
        component: () => import('@/views/system/user/index.vue'),
        meta: { 
          title: '用户管理',
          roles: ['admin']
        }
      }
    ]
  },
  {
    path: '/business',
    name: 'Business',
    redirect: '/business/product',
    meta: { 
      title: '业务管理',
      requiresAuth: true,
      roles: ['admin', 'editor'] // 管理员和编辑可以访问
    },
    children: [
      {
        path: 'product',
        name: 'ProductManagement',
        component: () => import('@/views/business/product/index.vue'),
        meta: { 
          title: '产品管理',
          roles: ['admin', 'editor']
        }
      },
      {
        path: 'order',
        name: 'OrderManagement',
        component: () => import('@/views/business/order/index.vue'),
        meta: { 
          title: '订单管理',
          roles: ['admin', 'editor']
        }
      }
    ]
  }
]

// 静态路由（无需权限的路由）
export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { 
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/views/layout/index.vue'),
    redirect: '/dashboard',
    meta: { 
      requiresAuth: true
    },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { 
          title: '数据看板',
          requiresAuth: true,
          roles: ['admin', 'editor', 'user'] // 所有登录用户都可以访问
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/components/error/404.vue'),
    meta: { 
      title: '页面不存在',
      requiresAuth: false
    }
  }
]

export const usePermissionStore = defineStore('permission', () => {
  const routes = ref([])
  const addRoutes = ref([])
  const permissions = ref([])
  
  // 根据角色过滤路由
  function filterAsyncRoutes(routes, roles) {
    const res = []
    
    routes.forEach(route => {
      const tmp = { ...route }
      
      if (hasPermission(roles, tmp)) {
        if (tmp.children) {
          tmp.children = filterAsyncRoutes(tmp.children, roles)
        }
        res.push(tmp)
      }
    })
    
    return res
  }
  
  // 检查是否有权限
  function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
      return roles.some(role => route.meta.roles.includes(role))
    }
    return true
  }
  
  // 生成动态路由
  function generateRoutes(roles) {
    return new Promise((resolve) => {
      let accessedRoutes = []
      
      if (roles.includes('admin')) {
        // 管理员拥有所有权限
        accessedRoutes = asyncRoutes
      } else {
        // 其他角色根据权限过滤
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      
      routes.value = constantRoutes.concat(accessedRoutes)
      addRoutes.value = accessedRoutes
      
      // 添加到路由器
      accessedRoutes.forEach(route => {
        router.addRoute(route)
      })
      
      console.log('生成的路由:', routes.value)
      resolve(accessedRoutes)
    })
  }
  
  // 重置路由
  function resetRoutes() {
    // 移除动态添加的路由
    addRoutes.value.forEach(route => {
      const routeName = route.name
      if (routeName && router.hasRoute(routeName)) {
        router.removeRoute(routeName)
      }
    })
    
    routes.value = []
    addRoutes.value = []
  }
  
  // 获取用户权限列表
  function setPermissions(userPermissions) {
    permissions.value = userPermissions
  }
  
  // 检查是否有特定权限
  function hasAccess(permission) {
    return permissions.value.includes(permission)
  }
  
  // 获取侧边栏菜单（过滤掉没有children的路由）
  function getSidebarRoutes() {
    return routes.value.filter(route => 
      route.meta && !route.meta.hidden && route.children && route.children.length > 0
    )
  }
  
  return {
    routes,
    addRoutes,
    permissions,
    generateRoutes,
    resetRoutes,
    setPermissions,
    hasAccess,
    getSidebarRoutes,
    filterAsyncRoutes,
    hasPermission
  }
})